package com.yshkj.payment.service.impl;

import com.yshkj.payment.dto.AccountMenuListJsonDto;
import com.yshkj.payment.entity.Account;
import com.yshkj.payment.entity.Privilege;
import com.yshkj.payment.repository.AccountRepository;
import com.yshkj.payment.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by 唐旭 on 2016/9/22.
 */
@Service
@Transactional
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountRepository accountRepository;

    /**
     * Locates the user based on the username. In the actual implementation, the search
     * may possibly be case sensitive, or case insensitive depending on how the
     * implementation instance is configured. In this case, the <code>UserDetails</code>
     * object that comes back may have a username that is of a different case than what
     * was actually requested..
     *
     * @param username the username identifying the user whose data is required.
     * @return a fully populated user record (never <code>null</code>)
     * @throws UsernameNotFoundException if the user could not be found or the user has no
     *                                   GrantedAuthority
     */
    @Override
    @Transactional(readOnly = true)
//    @Cacheable(value = "Account", key = "#username")
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Account account = accountRepository.findTop1ByUsername(username);
        if (account == null) {
            throw new UsernameNotFoundException(String.format("未找到账号为:[%s]的用户", username));
        }
        return account;
    }

    @Override
    public AccountMenuListJsonDto getMenuList() {
        Account account = (Account) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<Privilege> privilegeTree = account.getPrivilegeTree();
        return new AccountMenuListJsonDto(privilegeTree);
    }
}
